import { cloud, showToast, getStorageSync, setStorageSync } from '@tarojs/taro'
import { globalImportFonts } from '@/assets/FontsImport'
import './app.scss'
import { Provider } from 'react-redux'
import configStore from './store'
import { Component } from 'react'
import { GetUserApi, GetSpaceApi, GetArticleApi } from '@/api/index.js'

const store = configStore()

export default class App extends Component {
	constructor() {
		super()
	}

	state = {
		hasLogin: false,
	}

	async onLaunch() {
		cloud.init({
			traceUser: true,
		})

		globalImportFonts()

		await this.checkIfLogin()

		const userInfo = await this.getUserInfo()
		store.dispatch({
			type: 'UPDATE_USER',
			payload: userInfo,
		})

		const _CurrentUsingSpace = getStorageSync('current-using-space')

		const spaceid = _CurrentUsingSpace?._id || userInfo.space?.[0]?._id

		if (spaceid) {
			const space = await this.getCurrentUsingSpaceInfo(spaceid)
			store.dispatch({
				type: 'UPDATE_SPACE',
				payload: space,
			})
			const _CurrentUsingArticle = getStorageSync('current-using-article')
			const articleid = _CurrentUsingArticle?._id || space.article?.[0]?._id
			if (articleid) {
				this.getCurrentUsingArticle(articleid)
			}
		}
		const _RecentReadArticle = getStorageSync('recent-read-article') || {}

		Object.keys(_RecentReadArticle).forEach((key) => {
			const children = _RecentReadArticle[key].children
			const clone = []
			children.forEach((item) => {
				if (clone.findIndex((c) => c._id === item._id) === -1) {
					clone.push(item)
				}
			})
			_RecentReadArticle[key].children = clone
		})

		store.dispatch({
			type: 'UPDATE_RECENT',
			payload: _RecentReadArticle,
		})
	}

	async checkIfLogin() {
		return new Promise((resolve, reject) => {
			cloud
				.callFunction({
					name: 'gnLogin',
				})
				.then((res) => res.result)
				.then((res) => {
					if (res.code !== 0) {
						throw new Error('服务器异常')
					}
					resolve(res)
				})
				.catch((err) => {
					showToast({
						title: '服务器异常',
						icon: 'error',
						duration: 1000,
					})
					reject(err)
					throw err
				})
		})
	}

	/**
	 * 获取用户信息
	 */
	getUserInfo() {
		return new Promise((resolve, reject) => {
			GetUserApi()
				.then((data) => {
					resolve(data)
				})
				.catch((err) => {
					reject(err)
					throw err
				})
		})
	}

	/**
	 * 获取空间信息
	 * @param {string} id 空间id
	 */
	getCurrentUsingSpaceInfo(id) {
		return new Promise((resolve, reject) => {
			GetSpaceApi({ id })
				.then((data) => {
					resolve(data)
				})
				.catch((err) => {
					reject(err)
					throw err
				})
		})
	}

	/**
	 * 获取当前文章信息
	 * @param {String} id
	 */
	getCurrentUsingArticle(id) {
		GetArticleApi({ id }).then((data) => {
			store.dispatch({
				type: 'UPDATE_ARTICLE',
				payload: data,
			})
		})
	}

	render() {
		return <Provider store={store}>{this.props.children}</Provider>
	}
}
